import 'package:flutter/material.dart';
import '../../models/post_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/image_utils.dart';

class PostDetailPage extends StatefulWidget {
  final PostModel post;

  const PostDetailPage({
    super.key,
    required this.post,
  });

  @override
  State<PostDetailPage> createState() => _PostDetailPageState();
}

class _PostDetailPageState extends State<PostDetailPage> {
  final ApiService _apiService = ApiService();
  late PostModel _post;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _post = widget.post;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('动态详情'),
        actions: [
          // 操作菜单
          PopupMenuButton<String>(
            onSelected: (value) => _handlePostAction(value),
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'edit',
                child: Row(
                  children: [
                    Icon(Icons.edit, size: 16),
                    SizedBox(width: 8),
                    Text('编辑'),
                  ],
                ),
              ),
              PopupMenuItem(
                value: _post.visibility == 'private' ? 'make_public' : 'make_private',
                child: Row(
                  children: [
                    Icon(
                      _post.visibility == 'private' ? Icons.public : Icons.lock,
                      size: 16,
                    ),
                    const SizedBox(width: 8),
                    Text(_post.visibility == 'private' ? '设为公开' : '设为私密'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'delete',
                child: Row(
                  children: [
                    Icon(Icons.delete, color: Colors.red, size: 16),
                    SizedBox(width: 8),
                    Text('删除', style: TextStyle(color: Colors.red)),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户信息
                  Row(
                    children: [
                      ImageUtils.safeAvatarImage(_post.userAvatar, size: 50),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              _post.username,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            Text(
                              _getTimeAgo(_post.createdAt),
                              style: TextStyle(
                                color: Colors.grey[600],
                                fontSize: 12,
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 隐私状态指示器
                      if (_post.visibility == 'private')
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.orange[100],
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                Icons.lock,
                                size: 12,
                                color: Colors.orange[700],
                              ),
                              const SizedBox(width: 4),
                              Text(
                                '私密',
                                style: TextStyle(
                                  color: Colors.orange[700],
                                  fontSize: 10,
                                ),
                              ),
                            ],
                          ),
                        ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  
                  // 动态内容
                  Text(
                    _post.content,
                    style: const TextStyle(fontSize: 16),
                  ),
                  
                  // 图片
                  if (_post.images.isNotEmpty) ...[
                    const SizedBox(height: 16),
                    _buildImageGrid(_post.images),
                  ],
                  
                  const SizedBox(height: 24),
                  
                  // 互动统计
                  Row(
                    children: [
                      _buildStatItem(Icons.favorite, '${_post.likesCount}'),
                      const SizedBox(width: 24),
                      _buildStatItem(Icons.comment, '${_post.commentsCount}'),
                      const SizedBox(width: 24),
                      _buildStatItem(Icons.share, '${_post.sharesCount}'),
                      const SizedBox(width: 24),
                      _buildStatItem(Icons.visibility, '${_post.viewsCount}'),
                    ],
                  ),
                  
                  const SizedBox(height: 32),
                  
                  // 操作按钮
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () => _setPostVisibility(
                            _post.visibility == 'private' ? 'public' : 'private'
                          ),
                          icon: Icon(
                            _post.visibility == 'private' ? Icons.public : Icons.lock,
                          ),
                          label: Text(_post.visibility == 'private' ? '设为公开' : '设为私密'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: _post.visibility == 'private' 
                                ? Colors.green 
                                : Colors.orange,
                            foregroundColor: Colors.white,
                          ),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: () => _deletePost(),
                          icon: const Icon(Icons.delete),
                          label: const Text('删除'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red,
                            foregroundColor: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
    );
  }

  Widget _buildStatItem(IconData icon, String count) {
    return Row(
      children: [
        Icon(icon, size: 20, color: Colors.grey[600]),
        const SizedBox(width: 4),
        Text(
          count,
          style: TextStyle(
            color: Colors.grey[600],
            fontSize: 14,
          ),
        ),
      ],
    );
  }

  Widget _buildImageGrid(List<String> images) {
    if (images.length == 1) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.network(
          images[0],
          width: double.infinity,
          height: 200,
          fit: BoxFit.cover,
        ),
      );
    } else {
      return GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: images.length > 9 ? 9 : images.length,
        itemBuilder: (context, index) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.network(
              images[index],
              fit: BoxFit.cover,
            ),
          );
        },
      );
    }
  }

  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  // 处理动态操作
  void _handlePostAction(String action) {
    switch (action) {
      case 'edit':
        _editPost();
        break;
      case 'make_private':
        _setPostVisibility('private');
        break;
      case 'make_public':
        _setPostVisibility('public');
        break;
      case 'delete':
        _deletePost();
        break;
    }
  }

  // 编辑动态
  void _editPost() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('编辑功能开发中...')),
    );
  }

  // 设置动态隐私
  void _setPostVisibility(String visibility) {
    final visibilityText = visibility == 'private' ? '私密' : '公开';
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('设为$visibilityText'),
        content: Text('确定要将此动态设为$visibilityText吗？${visibility == 'private' ? '设为私密后只有您自己可以看到。' : '设为公开后所有人都可以看到。'}'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              setState(() {
                _isLoading = true;
              });
              
              try {
                await _apiService.setPostVisibility(_post.id, visibility);
                setState(() {
                  _post = PostModel(
                    id: _post.id,
                    userId: _post.userId,
                    username: _post.username,
                    userAvatar: _post.userAvatar,
                    postType: _post.postType,
                    content: _post.content,
                    coverUrl: _post.coverUrl,
                    images: _post.images,
                    likesCount: _post.likesCount,
                    commentsCount: _post.commentsCount,
                    sharesCount: _post.sharesCount,
                    viewsCount: _post.viewsCount,
                    isHot: _post.isHot,
                    skillTags: _post.skillTags,
                    createdAt: _post.createdAt,
                    isLiked: _post.isLiked,
                    isFollowed: _post.isFollowed,
                    visibility: visibility, // 更新隐私设置
                  );
                  _isLoading = false;
                });
                
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('动态已设为$visibilityText')),
                );
              } catch (e) {
                setState(() {
                  _isLoading = false;
                });
                Logger.e('SET_VISIBILITY', '设置隐私失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('设置失败: $e')),
                );
              }
            },
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  // 删除动态
  void _deletePost() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除动态'),
        content: const Text('确定要删除此动态吗？删除后将无法恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              setState(() {
                _isLoading = true;
              });
              
              try {
                await _apiService.deletePost(_post.id);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('动态已删除')),
                );
                // 返回上一页
                Navigator.pop(context);
              } catch (e) {
                setState(() {
                  _isLoading = false;
                });
                Logger.e('DELETE_POST', '删除动态失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('删除失败: $e')),
                );
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}
